package com.wxb.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.wxb.common.core.utils.StringUtils;
import com.wxb.common.core.web.controller.BaseController;
import com.wxb.common.security.utils.SecurityUtils;
import com.wxb.domain.MallOrderEntity;
import com.wxb.domain.MallOrderGoodsEntity;
import com.wxb.service.IMallOrderGoodsService;
import com.wxb.service.IMallOrderService;
import com.wxb.service.impl.MallKdniaoServiceImpl;
import com.wxb.service.impl.MallWeixinPayServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Date 2025-05-30 10:09
 * @Version 1.0
 * @Description
 * @ClassName MallOrderController
 **/
@RestController
@RequestMapping("/order")
public class MallOrderController extends BaseController {
    @Resource
    private IMallOrderService orderService;
    @Resource
    private IMallOrderGoodsService orderGoodsService;
    @Resource
    private MallKdniaoServiceImpl apiKdniaoService;
    @Resource
    private MallWeixinPayServiceImpl weixinPayService;
    /**
     * 得到request对象
     */
    @Autowired
    protected HttpServletRequest request;

    /**
     *
     */
    @PostMapping("index")
    public Object index() {
        return success("");
    }

    /**
     * 获取订单列表
     */
    @ApiOperation(value = "获取订单列表")
    @PostMapping("list")
    public Object list() {
        startPage();
        Map<String, Object> params = new HashMap<>();
        params.put("sidx", "add_time");
        params.put("order", "desc");
        //查询列表数据
        List<MallOrderEntity> orderEntityList = orderService.queryList(params);
        for (MallOrderEntity item : orderEntityList) {
            Map<String, Object> orderGoodsParam = new HashMap<>();
            orderGoodsParam.put("orderId", item.getId());
            //订单的商品
            List<MallOrderGoodsEntity> goodsList = orderGoodsService.queryList(orderGoodsParam);
            Integer goodsCount = 0;
            for (MallOrderGoodsEntity orderGoodsEntity : goodsList) {
                goodsCount += orderGoodsEntity.getNumber();
                item.setGoodsCount(goodsCount);
            }
        }
        return getDataTable(orderEntityList);
    }

    /**
     * 获取订单详情
     */
    @ApiOperation(value = "获取订单详情")
    @PostMapping("detail")
    public Object detail(Integer orderId) {
        Map<String, Object> resultObj = new HashMap<>();
        //
        MallOrderEntity orderInfo = orderService.queryObject(orderId);
        if (null == orderInfo) {
            return error("订单不存在");
        }

        if (!SecurityUtils.getUserId().equals(orderInfo.getUserId())) {
            return error("越权操作！");
        }
        Map<String, Object> orderGoodsParam = new HashMap<>();
        orderGoodsParam.put("orderId", orderId);
        //订单的商品
        List<MallOrderGoodsEntity> orderGoods = orderGoodsService.queryList(orderGoodsParam);
        //订单最后支付时间
        if (orderInfo.getOrderStatus() == 0) {
            // if (moment().subtract(60, 'minutes') < moment(orderInfo.addTime)) {
//            orderInfo.final_pay_time = moment("001234", "Hmmss").format("mm:ss")
            // } else {
            //     //超过时间不支付，更新订单状态为取消
            // }
        }

        //订单可操作的选择,删除，支付，收货，评论，退换货
        Map<String, Object> handleOption = orderInfo.getHandleOption();
        //
        resultObj.put("orderInfo", orderInfo);
        resultObj.put("orderGoods", orderGoods);
        resultObj.put("handleOption", handleOption);
        if (StringUtils.isEmpty(orderInfo.getShippingCode()) && StringUtils.isNotEmpty(orderInfo.getShippingNo())) {
            // 快递
            List traces = apiKdniaoService.getOrderTracesByJson(orderInfo.getShippingCode(), orderInfo.getShippingNo());
            resultObj.put("shippingList", traces);
        }
        return success(resultObj);
    }

    @ApiOperation(value = "修改订单")
    @PostMapping("updateSuccess")
    public Object updateSuccess(Integer orderId) {
        MallOrderEntity orderInfo = orderService.queryObject(orderId);
        if (orderInfo == null) {
            return error("订单不存在");
        } else if (orderInfo.getOrderStatus() != 0) {
            return error("订单状态不正确orderStatus" + orderInfo.getOrderStatus() + "payStatus" + orderInfo.getPayStatus());
        }

        if (!SecurityUtils.getUserId().equals(orderInfo.getUserId())) {
            return error("越权操作！");
        }
        orderInfo.setId(orderId);
        orderInfo.setPayStatus(2);
        orderInfo.setOrderStatus(201);
        orderInfo.setShippingStatus(0);
        orderInfo.setPayTime(new Date());
        int num = orderService.update(orderInfo);
        if (num > 0) {
            return success("修改订单成功");
        } else {
            return error("修改订单失败");
        }
    }

    /**
     * 获取订单列表
     */
    @ApiOperation(value = "订单提交")
    @PostMapping("submit")
    public Object submit() {
        Map<String, Object> resultObj = null;
        try {
            resultObj = orderService.submit(getJsonRequest(), SecurityUtils.getUserId());
            if (null != resultObj) {
                return toResponsObject(MapUtils.getInteger(resultObj, "errno"), MapUtils.getString(resultObj, "errmsg"), resultObj.get("data"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return error("提交失败");
    }

    public JSONObject getJsonRequest() {
        JSONObject result = null;
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader();) {
            char[] buff = new char[1024];
            int len;
            while ((len = reader.read(buff)) != -1) {
                sb.append(buff, 0, len);
            }
            result = JSONObject.parseObject(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }
    /**
     * @param requestCode
     * @param msg
     * @param data
     * @return Map<String, Object>
     * @throws
     * @Description:构建统一格式返回对象
     * @date 2016年9月2日
     * @author zhuliyun
     */
    public Map<String, Object> toResponsObject(int requestCode, String msg, Object data) {
        Map<String, Object> obj = new HashMap<String, Object>();
        obj.put("errno", requestCode);
        obj.put("errmsg", msg);
        if (data != null) {
            obj.put("data", data);
        }
        return obj;
    }
    /**
     * 取消订单
     */
    @ApiOperation(value = "取消订单")
    @PostMapping("cancelOrder")
    public Object cancelOrder(Integer orderId) throws Exception {

        MallOrderEntity orderVo = orderService.queryObject(orderId);
        if (null == orderVo) {
            return error("订单不存在！");
        }
        if (!SecurityUtils.getUserId().equals(orderVo.getUserId())) {
            return error("越权操作！");
        }
        if (orderVo.getOrderStatus() == 300) {
            return error("已发货，不能取消");
        } else if (orderVo.getOrderStatus() == 301) {
            return error("已收货，不能取消");
        }
        // 需要退款
        if (orderVo.getPayStatus() == 2) {
            WxPayRefundResult result = weixinPayService.refund(orderVo.getOrderSn(),
                    0.01, 0.01);
            if ("SUCCESS".equals(result.getResultCode())) {
                if (orderVo.getOrderStatus() == 201) {
                    orderVo.setOrderStatus(401);
                } else if (orderVo.getOrderStatus() == 300) {
                    orderVo.setOrderStatus(402);
                }
                orderVo.setPayStatus(4);
                orderService.update(orderVo);
                return success("取消成功");
            } else {
                return toResponsObject(400, "取消成失败", "");
            }
        } else {
            orderVo.setOrderStatus(101);
            orderService.update(orderVo);
            return this.success("取消成功");
        }
    }

    /**
     * 确认收货
     */
    @ApiOperation(value = "确认收货")
    @PostMapping("confirmOrder")
    public Object confirmOrder(Integer orderId) {
        try {
            MallOrderEntity orderVo = orderService.queryObject(orderId);
            if (null == orderVo) {
                return error("订单不存在！");
            }
            if (!SecurityUtils.getUserId().equals(orderVo.getUserId())) {
                return success("越权操作！");
            }
            orderVo.setOrderStatus(301);
            orderVo.setShippingStatus(2);
            orderVo.setConfirmTime(new Date());
            orderService.update(orderVo);
            return this.success("确认收货成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return error("提交失败");
    }
}
